package com.wzy.lock;


import org.apache.zookeeper.*;

import java.io.IOException;
import java.util.concurrent.CountDownLatch;

/**
 * 描述  : 注意: zookeeper 原生api 不支持递归创建节点
 * 创建人:    Wzy
 * 创建时间: 2020-06-06  23:22
 */
public class ZKLock {
    private ZooKeeper zooKeeper;

    private CountDownLatch countDownLatch = new CountDownLatch(1);

    private ZKLock() {
        try {
            zooKeeper = new ZooKeeper("localhost:2181", 5000, new ZKWatcher());
            System.out.println(zooKeeper.getState());
            countDownLatch.await();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static ZKLock getInstance() {
        return Singleton.getInstance();
    }

    /**
     * zk 实现分布式锁
     *
     * @param id
     */
    public void lock(Integer id) {
        String path = "/xdclass-product-lock-" + id;
        //创建临时节点 ,宕机自动释放
        try {
            zooKeeper.create(path, "".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
        } catch (KeeperException e) {
            //尝试创建,如果失败表示获取锁失败,进行循环尝试
            while (true) {
                try {
                    Thread.sleep(500L);
                } catch (InterruptedException interruptedException) {
                    interruptedException.printStackTrace();
                }
                try {
                    zooKeeper.create(path, "".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
                } catch (Exception e1) {
                    continue;
                }
                break;
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    /**
     * 释放锁,删除zk节点
     *
     * @param id
     */
    public void unlock(Integer id) {
        String path = "/xdclass-product-lock-" + id;
        try {
            //-1 代表不限定版本
            zooKeeper.delete(path, -1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (KeeperException e) {
            e.printStackTrace();
        }
    }


    private class ZKWatcher implements Watcher {
        public void process(WatchedEvent watchedEvent) {
            System.out.println("监听到事件>>>>>" + watchedEvent);
            if (Event.KeeperState.SyncConnected == watchedEvent.getState()) {
                countDownLatch.countDown();
            }
        }
    }


    private static class Singleton {
        private Singleton() {
        }

        private static final ZKLock instance = new ZKLock();

        public static ZKLock getInstance() {
            return instance;
        }
    }
}
